<template>
  <!-- 最外层的容器 -->
  <view class="my-checkout-container">
    <!-- 全选区域 -->
    <label class="radio">
      <radio color="#C00000" :checked="isCheckedAll" @click="onCheckedAll" />
      <text>全选</text>
    </label>

    <!-- 合计区域 -->
    <view class="amount-box">
      合计:<text class="amount">{{ checkedAmount | formatPrice }}</text>
    </view>

    <!-- 结算按钮 -->
    <view class="btn-checkout" @click="checkout">结算({{ checkedTotal }})</view>
  </view>
</template>

<script>
import { mapGetters, mapState } from "vuex";
export default {
  data() {
    return {
      seconds: 3,
      timer: null,
    };
  },
  computed: {
    ...mapGetters("cart", ["checkedTotal", "total", "checkedAmount"]),
    ...mapGetters("user", ["fullAddress"]),
    ...mapState("user", ["token"]),
    // 全选组件的勾选状态
    isCheckedAll() {
      return this.checkedTotal === this.total;
    },
  },
  methods: {
    onCheckedAll() {
      this.$store.commit("cart/updateAllGoodsState", !this.isCheckedAll);
    },
    // 1. 去结算
    checkout() {
      console.log(this.fullAddress);
      // 1.1 是否已勾选要结算的商品
      if (this.checkedTotal === 0) return this.$msg("请勾选要结算的商品");
      // 1.2 是否已选择收货地址
      if (!this.fullAddress) return this.$msg("请选择收货地址");
      // 1.3 是否已登录
      if (!this.token) {
        return this.delayJump();
      }
      // 1.4 创建订单进行微信支付
      this.payOrder();
    },
    // 2. 倒计时3s跳转我的页面
    delayJump() {
      // 2.1 重置倒计时秒数
      this.seconds = 3;
      // 2.2 初次展示提示消息
      this.$msg("请登录后再结算！" + this.seconds + " 秒后自动跳转到登录页");
      // 2.3 开始定时器
      this.timer = setInterval(() => {
        this.seconds--;
        if (this.seconds > 0) {
          this.$msg(
            "请登录后再结算！" + this.seconds + " 秒后自动跳转到登录页"
          );
        } else {
          clearInterval(this.timer);

          // 记录当前页面的路径和跳转方式
          this.$store.commit("user/setRedirectInfo", {
            url: "/pages/cart/cart",
            type: "tab",
          });

          uni.switchTab({
            url: "/pages/my/my",
          });
        }
      }, 1000);
    },
    // 微信支付
    async payOrder() {
      // 1. 创建订单
      // 1.1 发送请求
      const { meta, message } = await this.$http.post("/my/orders/create", {
        // 开发期间不填写真实的订单价格，写死订单总价为1分钱
        order_price: 0.01,
        // 收获地址
        consignee_addr: this.fullAddress,
        // 购物车中选中的商品
        goods: this.$store.state.cart.carItems
          .filter((x) => x.goods_state)
          .map((x) => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price,
          })),
      });

      if (meta.status !== 200) {
        return this.$msg("创建订单失败！");
      }

      // 1.2 得到 “订单编号”
      console.log(message);
      const orderNumber = message.order_number;

      // -------------------------------------------
      // 2. 订单预支付(获取支付参数)
      // 2.1 请求获取订单的支付信息
      const { meta: meta2, message: message2 } = await this.$http.post(
        "/my/orders/req_unifiedorder",
        {
          order_number: orderNumber,
        }
      );

      // 2.2 预付订单生成失败
      if (meta2.status !== 200) {
        return this.$msg("预付订单生成失败！");
      }

      // 2.3 得到订单支付相关的必要参数
      console.log(message2);
      const payInfo = message2.pay;

      // -----------------------------------
      // 3. 发起微信支付
      try {
        // 3.1 弹出微信支付界面
        await uni.requestPayment(payInfo);
        // 3.2 查询支付结果
        const { meta: meta3, message: message3 } = await this.$http.post(
          "/my/orders/chkOrder",
          {
            order_number: orderNumber,
          }
        );

        if (meta3.status !== 200) {
          return this.$msg("订单支付失败！");
        }
        // 3.3 提示支付完成
        this.$msg("订单支付成功");
      } catch (error) {
        this.$msg("用户取消支付");
        // 去我的订单页面
        uni.switchTab({
          url: "/pages/my/my",
        });
      }

      // if (err) {
      //   return this.$msg("订单支付失败！");
      // }
    },
  },
};
</script>

<style lang="scss">
.my-checkout-container {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100rpx;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10rpx;
  font-size: 28rpx;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-checkout {
    height: 100rpx;
    min-width: 200rpx;
    background-color: #c00000;
    color: white;
    line-height: 100rpx;
    text-align: center;
    padding: 0 20rpx;
  }
}
</style>
